package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.vo.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService userMember;

    @RequestMapping("/check")
    public Result check(@RequestBody LoginInfo loginInfo) {
        String telephone = loginInfo.getTelephone();
        String validateCode = loginInfo.getValidateCode();

        String redisCode = jedisPool.getResource().get(RedisMessageConstant.SENDTYPE_LOGIN + telephone);
        //校验验证码
        if (null == redisCode || !redisCode.equals(validateCode)) {
            return Result.error("验证码错误！");
        }
        //检查当前用户是否存在
        Member member = userMember.findByTelephone(telephone);
        //创建用户
        if (null==member){
            member=new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            userMember.add(member);
        }

        //成功token（可用雪花算法）
        String token = UUID.randomUUID().toString();
        //将用户存储到redis
        jedisPool.getResource().setex(token,60*60*24*15, JSON.toJSONString(member));
        return Result.success(MessageConstant.LOGIN_SUCCESS,token);
    }

}
